'use strict';

const Controller = require('egg').Controller;

class table extends Controller {
  // 查表
  async query() {
    const { ctx, service } = this;
    const body = ctx.request.merge({
      id: null,
      name: null,
      ...ctx.request.paging(ctx.request.body),
    }, ctx.request.body);

    const data = await service.table.query(...Object.values(body));
    ctx.body = ctx.response.successResult(2001, data);
  }

  // 建表
  async create() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      name: '',
      power_role: null,
      index: 0,
    }, ctx.request.body);

    const valid = app.checkAND([ body.name ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }

    const data = await service.table.create(...Object.values(body));
    if (!data) {
      ctx.body = ctx.response.errResult(4002);
      return;
    }
    ctx.body = ctx.response.successResult(2001);
  }

  // 更新表
  async update() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      id: null,
      name: '',
      power_role: null,
      index: null,
    }, ctx.request.body);

    const valid = app.checkAND([
      { value: body.id, type: 'int' },
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }
    const data = await service.table.update(...Object.values(body));
    if (!data) {
      ctx.body = ctx.response.errResult(4002);
      return;
    }
    ctx.body = ctx.response.successResult(2001);
  }

  // 删表
  async delete() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      ids: [],
    }, ctx.request.body);

    const valid = app.checkAND([
      { value: body.ids, type: 'hasArray' },
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }
    await service.table.delete(body.ids);
    ctx.body = ctx.response.successResult(2001);
  }

  // 导入表
  async import() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      name: '',
      fields: [],
      rows: [],
    }, ctx.request.body);

    const valid = app.checkAND([
      body.name,
      { value: body.fields, type: 'hasArray' },
      { value: body.rows, type: 'hasArray' },
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }

    const data = await service.table.import(body.name, body.fields, body.rows);
    if (!data) {
      ctx.body = ctx.response.errResult(4002);
      return;
    }
    ctx.body = ctx.response.successResult(2001);
  }
}

module.exports = table;
